# -*- coding: utf-8 -*-
import json
import time;
import chaosdb,contact2;
import event;

recommendDic = [];

def addNewRecommendation(rItem):
    recommendDic.append(rItem);
    song = chaosdb.getTrack(int(rItem.info['sid']));
    if(song==None):
        chaosdb.addTrack(rItem.info);
    else:
        if(song.ssid !=rItem.info['ssid']):
            chaosdb.updateTrackSSID(rItem.info['sid'], rItem.info['ssid']);
            
    #TODO:CHECK THE AUTHENTICATION
    rid = chaosdb.addRecommendation(rItem.sourceUID, rItem.destUID, rItem.info['sid']);
    return rid;

def addNewRes(rItem,destUIDs):
    song = chaosdb.getTrack(int(rItem.info['sid']));
    if(song==None):
        chaosdb.addTrack(rItem.info);
    else:
        if(song.ssid!=rItem.info['ssid']):
            chaosdb.updateTrackSSID(rItem.info['sid'], rItem.info['ssid']);
    
    #TODO:CHECK THE AUTHENTICATION
    rid = chaosdb.addRecomendations(rItem.sourceUID,destUIDs,rItem.info['sid']);
    return rid;


def needUpdateUserInfo(dbUser,name,uidstr,headimg,version):
    return dbUser.name==name and dbUser.dbuid==uidstr and dbUser.version==version and dbUser.headimg == headimg;

def registerUser(uid,name,url,uidstr,headimg,version):
    dbUser = getUser(uid)
    if(dbUser!=None and dbUser.isactivate == 1):
        if(needUpdateUserInfo(dbUser,name,uidstr,headimg,version)==False):
            chaosdb.updateDBUserInfo(uid,uidstr,name,url,headimg,version);
        else:
            chaosdb.updateDBUserTime(uid);
    else:
        if(dbUser!=None):
            sourceUIDS = [];
            recommends = chaosdb.getUnResponedReInDestId(uid, "2000-01-01 10:00:00");
            for recommend in recommends:
                sourceUID = recommend.sourceid;
                if((str(sourceUID) in sourceUIDS)==False):
                    sourceUIDS.append(str(sourceUID));
                    event.addEvent(sourceUID,event.TYPE_INVITED_UID_ACTTIVATE, "[type=user,id=%d,display=%s]开始使用Chaos了"%(uid, name.encode('utf-8')));
#                    except UnicodeDecodeError:
#                        pass;
            if(len(sourceUIDS)>=contact2.CONTACTS_MAX):
                sourceUIDS = sourceUIDS[0:contact2.CONTACTS_MAX];
            if(len(sourceUIDS)>0):
                for sourceuid in sourceUIDS:
                        event.addEvent(sourceuid,event.TYPE_ADD_AS_FROM_ID,"[type=user,id=%d,display=%s]添加你为Chaos推荐对象了"%(uid,name.encode('utf-8')));
#                except UnicodeDecodeError:
#                    pass;
            contactlistStr = ','.join(sourceUIDS);
            chaosdb.activateDBUser(uid,version,contactlistStr);
        else:
            chaosdb.addDBUser(uid,name,url,uidstr,headimg,version);


def getRecommendList(uid,startTime='2011-05-24 23:34:42'):
    chaosdb.updateDBUserTime(uid);
    dbList = chaosdb.getUnResponedReInDestId(uid,startTime);
    if(len(dbList)>0):
        tracks = {};
        list = [];
        
        for rDbItem in dbList:
            list.append(rDbItem);
            if((rDbItem.songid in tracks)==False):
#                trackRst = chaosdb.getTrackInfo(rDbItem.songid);
                track = chaosdb.getTrack(rDbItem.songid);
                if(track!=None):
                    tracks[rDbItem.songid] = track;
                else:
                    #delete the recommend item
                    chaosdb.db.delete('recommend',where="id=%d"%rDbItem.id);
                    chaosdb.db.delete('track',where="sid=%d"%rDbItem.songid);
                    #TODO: ADDING TO LOG 
        rItems = []
        print tracks[rDbItem.songid];
        for rDbItem in list:
            sourceUser = getUser(rDbItem.sourceid);
            if(sourceUser!=None):
                rItemDic = {"id":rDbItem.id,
                            "destUID":rDbItem.destid,
                            "sourceUID":rDbItem.sourceid,
                            "sourceAlias":sourceUser.dbuid,
                            "sourceName":sourceUser.name,
                            "sourceURL":sourceUser.dburl,
                            "time":time.mktime(rDbItem.time.timetuple()),
                            "trackInfo":json.dumps(tracks[rDbItem.songid])}
                rItems.append(json.dumps(rItemDic));
            else:
                #delete the recommend item
                chaosdb.db.delete('recommend',where="id=%d"%rDbItem.id);
#        rst = {'uid':uid,
#               'recommends':rItems}
        return rItems;
    else:
#        return {'uid':uid,'recommends':[]};
        return [];

            
def getUser(uid):
    idbrst = chaosdb.getDBUser(uid);
    return idbrst;

class DBUser:
    '''User @ Douban.com'''
    
    def __init__(self,uid,toListStr="",fromListStr=""):
        self.uid = uid;
        self.recommendList=[];
        if(toListStr!=None):
            self.toList=toListStr.split(',');
        if(fromListStr!=None):
            self.fromList=fromListStr.split(',');
        self.lastOpTime = time.time();

    def recommendToF(self,rItem):
        pass
    
    def receiveRecommendation(self,rItem):
        self.recommendList.append(rItem);
#        print "%d get a new song from %d"%self.uid%rItem.sourceUID

    def addFavToRecommendItem(self,rId):
        self.lastOpTime = time.time();
    
    def getContactList(self):
        self.lastOpTime = time.time();
        return self.toList;
    
    
class RecommendInfo:
    
    def __init__(self,infoDic,sourceUID,destUID):
        self.destUID = destUID;
        self.sourceUID = sourceUID;
        self.info = infoDic;
        pass
    
def generateReId():
    return len(recommendDic);